package com.angis.fx.activity.login;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.OnEditorActionListener;

import com.angis.fx.activity.R;
import com.angis.fx.activity.service.OnlineLoginService;
import com.angis.fx.activity.service.UploadLoginInfoService;
import com.angis.fx.activity.sxry.SxryMActivity;
import com.angis.fx.adapter.RadioAdapter;
import com.angis.fx.data.ContextInfo;
import com.angis.fx.db.XtszDBHelper;
import com.angis.fx.handler.login.DeviceRegisterHandler;
import com.angis.fx.handler.login.OnlineLoginHandler;
import com.angis.fx.handler.login.OutlineLoginHandler;
import com.angis.fx.util.CommonUtil;

public class LoginActivity extends Activity {
	
	private Button mOnlineLoginBt;
	private Button mOutlineLoginBt;
	public  EditText mUsername;
	private static EditText mPwd;
	public static EditText mIpAddress;
	public static String g_username;
	public static String g_password;
	public static String mLoginId;
	private ContextInfo mContextInfo;
	private List<CheckedTextView> mChooseCtv;
	private CheckedTextView mRadioTextView;
	private TextView mDeviceno;
	private TelephonyManager mTelManager;
	private String mHost = null;
	private String mTempHost;
	private LoginReceiver mReceiver;
	private Intent mIntent;
	private ProgressDialog mProgress;
	private Thread mThread;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		mOnlineLoginBt = (Button) findViewById(R.id.lg_onlinelogin_bt);
		mOutlineLoginBt = (Button) findViewById(R.id.lg_outlinelogin_bt);
		mUsername = (EditText) findViewById(R.id.lg_username_et);
		mPwd = (EditText) findViewById(R.id.lg_pwd_et);
		mIpAddress = (EditText) findViewById(R.id.ipaddress_et);
		mChooseCtv = new ArrayList<CheckedTextView>();
		mTelManager = CommonUtil.getTelephoneManager(LoginActivity.this);
		try {
			XtszDBHelper lDBHelper = new XtszDBHelper(LoginActivity.this);
			Cursor lCursor = lDBHelper.find();
			if(lCursor.getCount() > 0) {
				lCursor.moveToFirst();
				mHost = lCursor.getString(2);
				mIpAddress.setText(mHost);
			}
			lCursor.close();
			lDBHelper.closeDB();
			if(null == mHost || mHost.length() < 1) {
				lDBHelper.insert("3000", "500", "122.224.201.230");
				mIpAddress.setText("122.224.201.230");
				lDBHelper.closeDB();
			}
		}catch(Exception e) {
			
		}
		mTempHost = mIpAddress.getText().toString();
		mIpAddress.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if(!CommonUtil.validateIP(mIpAddress.getText().toString()))
		        {
					Toast.makeText(LoginActivity.this, "请输入正确的IP地址", Toast.LENGTH_SHORT).show();
					mIpAddress.setText(mTempHost);
					mIpAddress.requestFocus();
		        }
				return false;
			}
		});
		mOnlineLoginBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				g_username = mUsername.getText().toString();
				g_password = mPwd.getText().toString();
				if(g_username.length() == 0 || g_password.length() == 0) {
					mProgress.dismiss();
					Toast.makeText(LoginActivity.this, "用户名/密码不能为空!", Toast.LENGTH_SHORT).show();
				}
				try {
					mProgress = ProgressDialog.show(LoginActivity.this, "", "登录中...", true);
					mReceiver = new LoginReceiver();
					IntentFilter filter = new IntentFilter();
					filter.addAction("loginaction");
					LoginActivity.this.registerReceiver(mReceiver, filter);
					mIntent = new Intent(LoginActivity.this, OnlineLoginService.class);
					Bundle lBundle = new Bundle();
					lBundle.putString("username", mUsername.getText().toString());
					lBundle.putString("pwd", mPwd.getText().toString());
					//模拟器
					if(null == mTelManager.getDeviceId() || mTelManager.getDeviceId().contains("000000")) {
						lBundle.putString("deviceid", mTelManager.getDeviceId());
					}else {
						//真机
						lBundle.putString("deviceid", mTelManager.getDeviceId());
					}
					mIntent.putExtras(lBundle);
					 final Handler uiThreadCallback = new Handler();

					  // performs rendering in the "edt" thread, after background operation is complete
					  final Runnable runInUIThread = new Runnable() {
					    public void run() {
					    	LoginActivity.this.startService(mIntent);
					    }
					  };
					  mThread = new Thread() {
					    @Override public void run() {
					    	uiThreadCallback.post(runInUIThread);
					    }
					  };
					  mThread.start();
				} catch (Exception e) {
					mProgress.dismiss();
					Toast.makeText(LoginActivity.this, "连接服务器出错!", Toast.LENGTH_SHORT).show();
				}
//				ContextInfo lContextInfo = new ContextInfo();
//				lContextInfo.setLoginType(1);
//				lContextInfo.setDeviceid("AT00005");
//				
//				OrganizationInfo lOrganization = new OrganizationInfo();
//				lOrganization.setOid("0411291651049911");
//				lOrganization.setName("浙江省文化厅");
//				
//				UserInfo lUser = new UserInfo();
//				List<UserInfo> lUserInfos = new ArrayList<UserInfo>();
//				List<DepartmentInfo> lDepmentInfos = new ArrayList<DepartmentInfo>();
//				
//				DepartmentInfo lDepartment = new DepartmentInfo();
//				lDepartment.setPid("1050324081533345");
//				lDepartment.setName("厅领导");
//				lUser.setUid("yjx");
//				lUser.setName("杨");
//				lUserInfos.add(lUser);
//				lDepartment.setUserInfos(lUserInfos);
//				lDepmentInfos.add(lDepartment);
//				
//				lDepmentInfos = new ArrayList<DepartmentInfo>();
//				lDepartment = new DepartmentInfo();
//				lDepartment.setPid("1050714145902396");
//				lDepartment.setName("人事处");
//				lUserInfos = new ArrayList<UserInfo>();
//				lUser = new UserInfo();
//				lUser.setUid("zhh");
//				lUser.setName("海宏");
//				lUserInfos.add(lUser);
//				lDepartment.setUserInfos(lUserInfos);
//				lDepmentInfos.add(lDepartment);
//				
//				lDepmentInfos = new ArrayList<DepartmentInfo>();
//				lDepartment = new DepartmentInfo();
//				lDepartment.setPid("1050712175639796");
//				lDepartment.setName("厅办公室");
//				lUserInfos = new ArrayList<UserInfo>();
//				lUser = new UserInfo();
//				lUser.setUid("ldz");
//				lUser.setName("李中");
//				lUserInfos.add(lUser);
//				lDepartment.setUserInfos(lUserInfos);
//				lDepmentInfos.add(lDepartment);
//				
//				lDepartment = new DepartmentInfo();
//				lDepartment.setPid("1050610150713765");
//				lDepartment.setName("系统管理");
//				lUserInfos = new ArrayList<UserInfo>();
//				lUser = new UserInfo();
//				lUser.setUid("xz");
//				lUser.setName("徐周");
//				lUserInfos.add(lUser);
//				lDepartment.setUserInfos(lUserInfos);
//				lDepmentInfos.add(lDepartment);
//				
//				lOrganization.setDpmentInfos(lDepmentInfos);
//				lContextInfo.setOrganizationInfo(lOrganization);
//				
//				Bundle lBundle = new Bundle();
//				lBundle.putBoolean("isClear", true);
//				lBundle.putSerializable("contextInfo", lContextInfo);
//				Intent lIntent = new Intent(LoginActivity.this, SxryTabs.class);
//				lIntent.putExtras(lBundle);
//                LoginActivity.this.startActivity(lIntent);
//                LoginActivity.this.finish();
				
//				new Handler().postDelayed(new Runnable(){ 
//		            @Override  
//		            public void run() {  
//		            	Dialog dialog = new Dialog(LoginActivity.this);
//		                Intent mainIntent = new Intent(LoginActivity.this, SxryTabs.class);
//		                LoginActivity.this.startActivity(mainIntent);
//		                LoginActivity.this.finish();
//		            }     
//		        }, SPLASH_DISPLAY_LENGHT);  
			}
		});
		mOutlineLoginBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				g_username = mUsername.getText().toString();
				g_password = mPwd.getText().toString();
				if(g_username.length() == 0 || g_password.length() == 0) {
					Toast.makeText(LoginActivity.this, "用户名/密码不能为空!", Toast.LENGTH_SHORT).show();
				}
				ProgressDialog lProgress = ProgressDialog.show(LoginActivity.this, "", "登录中...", true);
				try {
					OutlineLoginHandler lHandler = new OutlineLoginHandler();
					mContextInfo = lHandler.login(LoginActivity.this, mUsername.getText().toString(), mPwd.getText().toString());
					Date curDate = new Date(System.currentTimeMillis());
					mContextInfo.setLoginTime(curDate);
					mLoginId = new StringBuilder().append(mContextInfo.getDeviceno()).
									append(new SimpleDateFormat("yyyyMMddHHmmss").format(mContextInfo.getLoginTime())).toString();
					mIntent = new Intent(LoginActivity.this, UploadLoginInfoService.class);
					mIntent.putExtra("contextinfo", mContextInfo);
					uploadLoginInfo();
					if(null != mContextInfo) {
						startService(mIntent);
						forwardSxryTabs();
					}else {
						lProgress.dismiss();
						Toast.makeText(LoginActivity.this, "用户名/密码错误!", Toast.LENGTH_SHORT).show();
					}
				} catch (Exception e) {
					lProgress.dismiss();
					Toast.makeText(LoginActivity.this, "用户名/密码错误!", Toast.LENGTH_SHORT).show();
				}
			}
		});
		
	}
	
	private void uploadLoginInfo(){
		Date curDate = new Date(System.currentTimeMillis());
		mContextInfo.setLoginTime(curDate);
		mLoginId = new StringBuilder().append(mContextInfo.getDeviceno()).
						append(new SimpleDateFormat("yyyyMMddHHmmss").format(mContextInfo.getLoginTime())).toString();
		Intent lIntent = new Intent(LoginActivity.this, UploadLoginInfoService.class);
		lIntent.putExtra("contextinfo", mContextInfo);
		startService(lIntent);
	}
	
	private void forwardSxryTabs() {
		Bundle lBundle = new Bundle();
		lBundle.putBoolean("isClear", true);
		lBundle.putSerializable("contextInfo", mContextInfo);
		Intent lIntent = new Intent(LoginActivity.this, SxryMActivity.class);
		lIntent.putExtras(lBundle);
		LoginActivity.this.startActivity(lIntent);
		LoginActivity.this.finish();
	}
	
	public class LoginReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			mProgress.dismiss();
			mThread.stop();
			LoginActivity.this.unregisterReceiver(mReceiver);
			if(null != intent && null != intent.getExtras()) {
				mContextInfo = (ContextInfo) intent.getExtras().getSerializable("results");
				if(null == mContextInfo) {
					Toast.makeText(LoginActivity.this, "用户名/密码错误!", Toast.LENGTH_SHORT).show();
					return;
				}
				int lFlag = mContextInfo.getLoginFlag();
				Date curDate = new Date(System.currentTimeMillis());
				mContextInfo.setLoginTime(curDate);
				mLoginId = new StringBuilder().append(mContextInfo.getDeviceno()).
								append(new SimpleDateFormat("yyyyMMddHHmmss").format(mContextInfo.getLoginTime())).toString();
				mIntent = new Intent(LoginActivity.this, UploadLoginInfoService.class);
				mIntent.putExtra("contextinfo", mContextInfo);
				if(0== lFlag){
					Toast.makeText(LoginActivity.this, "用户名/密码错误!", Toast.LENGTH_SHORT).show();
				}else if(1 == lFlag) {
					startService(mIntent);
					forwardSxryTabs();
				}else if(2 == lFlag) {
					String[] lDevicenos = mContextInfo.getDeviceno().split("\\^");
					if(lDevicenos.length > 0) {
						LayoutInflater layoutInflater = LayoutInflater.from(LoginActivity.this);
					    View lView = layoutInflater.inflate(R.layout.radio_dialog, null);
						RadioAdapter lRegisterDialogListAdapter = new RadioAdapter(LoginActivity.this);
						ListView lListView = (ListView)lView.findViewById(R.id.radio_dialoglist);
						lRegisterDialogListAdapter.setData(Arrays.asList(lDevicenos));
						lListView.setAdapter(lRegisterDialogListAdapter);
						lListView.setOnItemClickListener(new OnItemClickListener(){
							@Override
							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id) {
								mRadioTextView = (CheckedTextView) view.findViewById(R.id.radio_dialog_item_ctv);
								if(mRadioTextView.isChecked()){
									mRadioTextView.toggle();
								}else if(!mRadioTextView.isChecked()) {
									for(int i=0; i<mChooseCtv.size(); i++){
										CheckedTextView mRadio = (CheckedTextView)mChooseCtv.get(i);
										mRadio.setChecked(false);
									}
									mChooseCtv.add(mRadioTextView);
									mRadioTextView.setChecked(true);
								}
								mDeviceno = (TextView) view.findViewById(R.id.radio_dialog_item_name);
							}
						});
						new AlertDialog.Builder(LoginActivity.this)
							.setTitle("请先注册设备")
							.setView(lView)
							.setPositiveButton(R.string.confirm,
									new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog,
												int whichButton) {
											String deviceno = mDeviceno.getText().toString();
											String lResult = DeviceRegisterHandler.register(deviceno, mTelManager.getDeviceId());
											if("1".equals(lResult)) {
												OnlineLoginHandler.updateUserInfo(LoginActivity.this, mContextInfo);
												XtszDBHelper lDBHelper = new XtszDBHelper(LoginActivity.this);
												lDBHelper.update(null, null, mIpAddress.getText().toString());
												lDBHelper.closeDB();
												startService(mIntent);
												forwardSxryTabs();
											}else {
												Toast.makeText(LoginActivity.this, "注册失败!", Toast.LENGTH_SHORT).show();
											}
										}
									})
							.setNegativeButton(R.string.cancel,
									new DialogInterface.OnClickListener() {
										public void onClick(DialogInterface dialog,
												int whichButton) {
										}
									}).create().show();
					}
				}else if(3 == lFlag) {
					forwardSxryTabs();
				}
			}
		}
	}
	
}
